package lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author jiangwz
 * @create 2019/9/14.
 */
public class CyclicBarrierDemo {

    private int count = 6;

    /**
     * 原理 每个线程都会使 --count 自检 如果不是0 则await, 是0则 调用runnable的run方法 然后signalAll 所有等待线程
     * @param args
     */
    public static void main(String[] args){
//        CyclicBarrierDemo cyclicBarrierDemo = new CyclicBarrierDemo();
//        int count = --cyclicBarrierDemo.count;//先自检,然后赋值,所以count减了1
//        System.out.println(cyclicBarrierDemo.count);


        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()-> System.out.println("****龙珠已集齐,马上召唤神龙!!"));

        for (int i = 1; i <= 7; i++) {
            int temp = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "号玩家找到龙珠第" + temp + "个龙珠超");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "" + i).start();
        }

    }
}
